package com.shimao.celnet.payment.controller;


import com.shimao.celnet.payment.form.ASysPermissionForm;
import com.shimao.celnet.payment.model.ASysPermission;
import com.shimao.celnet.payment.service.ASysPermissionService;
import com.shimao.celnet.payment.shiro.ShiroService;
import com.shimao.celnet.payment.util.FinalUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by ensure on 2017/4/21.
 */
@Controller
@RequestMapping("/resources")
public class ASysPermissionController {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private ASysPermissionService aSysPermissionService;


    @Autowired
    private ShiroService shiroService;


    /**
     * 分页列表
     * @param formBean 页面对象
     * @param pageActionNm 分页提交按钮名称
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String getByPage(@ModelAttribute ASysPermissionForm formBean, String pageActionNm, Model model){
        logger.info("执行列表页面初始化开始");

        //当前页码设定
        int pageNum=FinalUtil.PAGE_Fist_NUM;
        if(formBean.isIsLastPage()){
            pageNum=formBean.getPages();
        }
        if(StringUtils.isNotEmpty(pageActionNm) && !"0".equals(pageActionNm)){
            pageNum=Integer.valueOf(pageActionNm);
        }

        //页面权限下拉框
        model.addAttribute("selectList", aSysPermissionService.getSelectList());

        //页面数据查询结果
        model.addAttribute("formBean", aSysPermissionService.getByPage(formBean, pageNum, FinalUtil.PAGE_LENGHT));

        return "permission/permissionList";
    }

    /**
     * 更新初始化
     * @param
     * @return
     */
    @RequestMapping("/addInfo")
    @ResponseBody
    public ASysPermission addInfo() {

        ASysPermission aSysPermission = new ASysPermission();

        return aSysPermission;
    }

    /**
     * 更新初始化
     * @param
     * @return
     */
    @RequestMapping("/editInfo")
    @ResponseBody
    public ASysPermission editInfo(@RequestBody  String guid) {

        ASysPermission aSysPermission = new ASysPermission();
        if(StringUtils.isNotEmpty(guid)) {
            //编辑数据取得
            aSysPermission = aSysPermissionService.getByKey(guid);

        }
        return aSysPermission;
    }

    /**
     * 新增保存
     * @param
     * @return
     */
    @RequestMapping("/addSave")
    public  @ResponseBody Map<String, Object> addSave(@RequestBody @Valid ASysPermission addForm,BindingResult result) {
        //返回map
        Map<String, Object> returnMap = new HashMap<String, Object>();

        //界面输入验证
        if (result.hasErrors()) {
            for(FieldError error:result.getFieldErrors()) {
                  returnMap.put(error.getField() + FinalUtil.VALID_MSG, error.getDefaultMessage());
                //验证错误==2
                returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_2);
            }
            return returnMap;
        }

            try{
                //数据新增，GUID取得
                aSysPermissionService.save(addForm);
           //更新权限
                shiroService.updatePermission();
                //新增成功消息==0
                returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_SCU_0);
//                returnMap.put(FinalUtil.ERROR_MSG,  FinalUtil.PAGE_ADD_SCU);
                logger.debug(FinalUtil.PAGE_ADD_SCU);

            } catch (Exception e) {
                //新增失败消息==1
                returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_1);
                returnMap.put(FinalUtil.ERROR_MSG,  FinalUtil.PAGE_ADD_ERR);
                e.printStackTrace();
                logger.error(FinalUtil.PAGE_ADD_ERR);
                logger.error(e);
            }

        return returnMap;
    }

    /**
     * 更新保存
     * @param
     * @return
     */
    @RequestMapping("/editSave")
    public  @ResponseBody Map<String, Object> editSave(@RequestBody @Valid ASysPermission editForm,BindingResult result) {
        //返回map
        Map<String, Object> returnMap = new HashMap<String, Object>();

        //界面输入验证
        if (result.hasErrors()) {
            for(FieldError error:result.getFieldErrors()) {
                  returnMap.put(error.getField() + FinalUtil.VALID_MSG, error.getDefaultMessage());
                //验证错误==2
                returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_2);
            }
            return returnMap;
        }

        String createUserGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        editForm.setUpdateUserGuid(createUserGuid);

        try{
            //数据修改
            editForm.setCreatedUserGuid(createUserGuid);
            aSysPermissionService.update(editForm);

            //更新权限
            shiroService.updatePermission();

            //成功消息==0
            returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_SCU_0);
//                returnMap.put(FinalUtil.ERROR_MSG,  FinalUtil.PAGE_UPD_SCU);
            logger.debug(FinalUtil.PAGE_UPD_SCU);
        } catch (Exception e) {
            //失败消息
            returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_1);
            returnMap.put(FinalUtil.ERROR_MSG,  FinalUtil.PAGE_UPD_ERR);
            e.printStackTrace();
            logger.error(FinalUtil.PAGE_UPD_ERR);
            logger.error(e);
        }

        return returnMap;
    }

    /**
     * 删除
     * @param permissionGuid
     * @return
     */
    @RequestMapping("/delete")
    public @ResponseBody Map<String, Object> delete(@RequestBody String permissionGuid){
        //返回map
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            //删除权限
             int renCnt = aSysPermissionService.delete(permissionGuid);
            if(renCnt<=0){
                returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_1);
                returnMap.put(FinalUtil.ERROR_MSG,  FinalUtil.PAGE_DEL_ERR);
                return returnMap;
            }
            //更新权限
            shiroService.updatePermission();

            //成功消息==0
            returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_SCU_0);
            logger.debug(FinalUtil.PAGE_DEL_SCU);
        } catch (Exception e) {
            //失败消息
            returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_1);
            returnMap.put(FinalUtil.ERROR_MSG,  FinalUtil.PAGE_DEL_ERR);
            e.printStackTrace();
            logger.error(FinalUtil.PAGE_DEL_ERR);
            logger.error(e);
        }

        return returnMap;
    }
}
